package cn.darkhorse.device.service.impl;

import cn.darkhorse.common.util.Base64Util;
import cn.darkhorse.device.mapper.MesCameraMapper;
import cn.darkhorse.device.pojo.MesCamera;
import cn.darkhorse.device.pojo.MesDeviceCameraMapping;
import cn.darkhorse.device.service.MesCameraService;
import cn.darkhorse.device.service.MesDeviceCameraMappingService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 摄像机设置 服务实现类
 * </p>
 *
 * @author maoguanjun
 * @since 2023-04-20
 */
@Service
public class MesCameraServiceImpl extends ServiceImpl<MesCameraMapper, MesCamera> implements MesCameraService {

    @Resource
    private MesDeviceCameraMappingService mesDeviceCameraMappingService;
    /**
     * 列表带分页
     *
     * @param name
     * @param area
     * @param ip
     * @return
     */
    @Override
    public List<MesCamera> listAll(String name, String area, String ip) {
        LambdaQueryWrapper<MesCamera> wrapper=new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(name)){
            wrapper.like(MesCamera::getName,name);
        }
        if(StringUtils.isNotBlank(area)){
            wrapper.like(MesCamera::getArea,area);
        }
        if(StringUtils.isNotBlank(ip)){
            wrapper.like(MesCamera::getIp,ip);
        }
        return list(wrapper);
    }

    /**
     * 保存
     *
     * @param mesCamera
     * @return
     */
    @Override
    public boolean saveEntity(MesCamera mesCamera) {
        LambdaQueryWrapper<MesCamera> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MesCamera::getName,mesCamera.getName());
        if(null!=mesCamera.getId()){
            wrapper.ne(MesCamera::getId,mesCamera.getId());
        }
        long count =count(wrapper);
        if(count>0){
            throw new ServiceException("同公司下监控名称不可重复!");
        }
        try {
            mesCamera.setPwd(Base64Util.encryptBASE64(mesCamera.getPwd().getBytes()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(null!=mesCamera.getId()){
            return updateById(mesCamera);
        }else{
            return save(mesCamera);
        }
    }

    /**
     * 删除
     *
     * @param cameraId
     * @return
     */
    @Override
    public boolean delete(Long cameraId) {
        LambdaQueryWrapper<MesDeviceCameraMapping> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MesDeviceCameraMapping::getCameraId,cameraId);
        long count=mesDeviceCameraMappingService.count(wrapper);
        if(count>0){
            throw new ServiceException("已被绑定，不可删除！");
        }else{
            return removeById(cameraId);
        }
    }

}
